<template>
  <div class="school-posts">
    <div class="section-header">
      <h2 class="section-title">帖子管理</h2>
      <div class="filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索帖子标题或内容"
          class="search-input"
          clearable
          @input="filterPosts"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-button type="primary" @click="$router.push('/publish')">发布新帖子</el-button>
      </div>
    </div>

    <!-- 帖子列表 -->
    <el-table
      v-loading="loading"
      :data="filteredPosts"
      style="width: 100%"
      stripe
      row-key="_id"
      empty-text="暂无帖子数据"
    >
      <el-table-column prop="image" label="封面" width="100">
        <template #default="scope">
          <div class="image-preview">
            <img
              v-if="scope.row.image"
              :src="`http://localhost:5000/uploads/${scope.row.image}`"
              alt="封面"
              class="post-image"
            />
            <div v-else class="no-image">无图</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip></el-table-column>

      <el-table-column prop="description" label="内容摘要" min-width="200" show-overflow-tooltip></el-table-column>

      <el-table-column prop="author" label="作者" width="120">
        <template #default="scope">
          <div class="author-info">
            <img
            :src="scope.row.authorimg ? `http://localhost:5000/uploads/${scope.row.authorimg}` : defaultTouxiang"
            class="author-avatar"
          />
            <span>{{ getAuthorName(scope.row) }}</span>
          </div>
        </template>
      </el-table-column>
      

      <el-table-column prop="createdAt" label="发布时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column prop="likes" label="点赞数" width="90" align="center">
        <template #default="scope">
          {{ scope.row.likes || 0 }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="viewPost(scope.row)"
          >查看</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmDeletePost(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total,prev, pager, next"
        :total="totalPosts"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 帖子详情对话框 -->
    <el-dialog
      title="帖子详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <div v-if="selectedPost" class="post-detail">
        <h2 class="post-title">{{ selectedPost.title }}</h2>

        <div class="post-author-info">
          <div class="author-avatar-container">
            <img
              :src="selectedPost.authorimg ? `http://localhost:5000/uploads/${selectedPost.authorimg}` : '../../assets/erji.png'"
              alt="作者头像"
              class="author-avatar-lg"
            />
          </div>
          <div class="author-detail">
            <div class="author-name">{{ getAuthorName(selectedPost) }}</div>
            <div class="post-time">{{ formatDate(selectedPost.createdAt) }}</div>
          </div>
        </div>

        <div v-if="selectedPost.image" class="post-image-container">
          <img
            :src="`http://localhost:5000/uploads/${selectedPost.image}`"
            alt="帖子图片"
            class="full-post-image"
          />
        </div>

        <div class="post-content">
          {{ selectedPost.description }}
        </div>

        <div class="post-stats">
          <div class="stat-item">
            <i class="el-icon-star-on"></i>
            <span>{{ selectedPost.likes || 0 }} 次点赞</span>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="danger" @click="deletePostFromDialog">删除帖子</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  schoolId: {
    type: String,
    required: true
  }
})

const router = useRouter()

// 数据状态
const posts = ref([])
const filteredPosts = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPosts = ref(0)
const searchQuery = ref('')
const detailDialogVisible = ref(false)
const selectedPost = ref(null)
const defaultTouxiang = '/src/assets/touxiang.png'
// 监听schoolId变化，重新加载数据
watch(() => props.schoolId, (newValue) => {
  if (newValue) {
    fetchPosts()
  }
})

// 获取学校帖子
const fetchPosts = async () => {
  if (!props.schoolId) return

  loading.value = true
  try {
    const response = await axios.get(`http://localhost:5000/schools/${props.schoolId}/posts`, {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })

    if (response.data && Array.isArray(response.data)) {
      posts.value = response.data
      filterPosts()
      totalPosts.value = response.data.length // 此处可能需要获取总数，根据API调整
    } else {
      posts.value = []
      filteredPosts.value = []
      totalPosts.value = 0
    }
  } catch (error) {
    console.error('获取学校帖子失败:', error)
    ElMessage.error('获取学校帖子失败')
  } finally {
    loading.value = false
  }
}

// 筛选帖子
const filterPosts = () => {
  if (!searchQuery.value) {
    filteredPosts.value = posts.value
  } else {
    const query = searchQuery.value.toLowerCase()
    filteredPosts.value = posts.value.filter(post =>
      (post.title && post.title.toLowerCase().includes(query)) ||
      (post.description && post.description.toLowerCase().includes(query))
    )
  }
}

// 获取作者名称
const getAuthorName = (post) => {
  if (post.author && typeof post.author === 'object' && post.author.username) {
    return post.author.username
  } else if (typeof post.author === 'string') {
    return post.author
  } else {
    return '匿名用户'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchPosts()
}

// 查看帖子
const viewPost = (post) => {
  selectedPost.value = post
  detailDialogVisible.value = true
}

// 确认删除帖子
const confirmDeletePost = (post) => {
  ElMessageBox.confirm(
    `确定要删除标题为"${post.title}"的帖子吗？`,
    '删除帖子',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deletePost(post._id)
  }).catch(() => {
    // 用户取消操作
  })
}

// 从对话框中删除帖子
const deletePostFromDialog = () => {
  if (selectedPost.value) {
    confirmDeletePost(selectedPost.value)
  }
}

// 删除帖子
const deletePost = async (postId) => {
  try {
    const token = localStorage.getItem('token')
    await axios.delete(`http://localhost:5000/posts/${postId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('帖子已成功删除')
    detailDialogVisible.value = false // 关闭详情对话框
    fetchPosts() // 刷新列表
  } catch (error) {
    console.error('删除帖子失败:', error)
    ElMessage.error('删除帖子失败')
  }
}

// 组件挂载时获取帖子列表
onMounted(() => {
  if (props.schoolId) {
    fetchPosts()
  }
})
</script>

<style scoped>
.school-posts {
  padding: 20px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.filters {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #777;
  font-size: 12px;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

/* 帖子详情对话框样式 */
.post-detail {
  padding: 20px;
  background-color: #1f1b24;
  border-radius: 8px;
}

.post-title {
  color: #fff;
  font-size: 24px;
  margin-bottom: 20px;
}

.post-author-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.author-avatar-container {
  margin-right: 15px;
}

.author-avatar-lg {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.author-detail {
  display: flex;
  flex-direction: column;
}

.author-name {
  color: #fff;
  font-weight: bold;
  margin-bottom: 5px;
}

.post-time {
  color: #999;
  font-size: 14px;
}

.post-image-container {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.full-post-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
}

.post-content {
  color: #eee;
  line-height: 1.6;
  font-size: 16px;
  margin-bottom: 20px;
}

.post-stats {
  display: flex;
  align-items: center;
  color: #999;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.stat-item i {
  margin-right: 5px;
  color: #00aeff;
}

/* Element Plus 组件样式重写 */
:deep(.el-table) {
  background-color: transparent;
  color: #eee;
}

:deep(.el-table th) {
  background-color: #1f1b24;
  color: #b0bec5;
  border-bottom-color: #333;
}

:deep(.el-table tr) {
  background-color: #28232e;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #23202a;
}

:deep(.el-table td) {
  border-bottom-color: #333;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #342e3d;
}

:deep(.el-input__inner), :deep(.el-textarea__inner) {
  background-color: #1f1b24;
  border-color: #444;
  color: #fff;
}

:deep(.el-input__inner:focus), :deep(.el-textarea__inner:focus) {
  border-color: #00aeff;
}

:deep(.el-dialog) {
  background-color: #28232e;
  border-radius: 10px;
}

:deep(.el-dialog__title) {
  color: #fff;
}

:deep(.el-dialog__body) {
  color: #b0bec5;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-table__empty-text) {
  color: #777;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}
</style>
